##PBAR_ReadFD.py

import os
import csv
import numpy as np
import time
import datetime

# define nice variables
def DetectorList():
    """Returns detector list; tuple of (plastic, liquid)"""
    plastic = np.arange(25)
    liquid = np.arange(25,40)
    return(plastic, liquid)

def DetectorPosition():
    """Returns detector position map"""
    plastic = np.arange(25)
    liquid = np.arange(25,40)
    return(plastic, liquid)

def ReadData(filePrefix, filePath):
    """Reads the csv file."""
    datt = list()
    for ff in range(40):
        ff = ff +1
        print(ff)
        fullFilename = filePath + '\\' + filePrefix + '_FD-det' + '%d' %ff + '.txt'
        print fullFilename
        fid = open(fullFilename, 'r')
        csvReaderObj = csv.reader(fid, delimiter = ',')
        dat = np.zeros((256, 256))
        for ii in range(32):
            startIndex = ii*8
            stopIndex = (ii+1)*8
            # make temporary array for storing
            temp = np.zeros((256,8))    
            for jj in range(256):  # read 256 rows of the 18 columns
                # truncate row number and last element (which is blank) and convert to float
                # read every other element because the other elements are sigma values
                a =  np.array(csvReaderObj.next())
                a[a == ''] = 0.0
                a = a[0:18]
                temp[jj,:] = a[1:-1:2].astype(float)
##            print(a)
            dat[:, startIndex:stopIndex] = temp
            # skip to lines
            csvReaderObj.next()
            csvReaderObj.next()
        fid.close()
        datt.append(dat)
    return datt

def WriteData(fullFilename, dat):
    """Write FD data to csv file"""
    # open file for writing
    fid = open(fullFilename, 'wb')
    csvWriterObj = csv.writer(fid, delimiter = ',')
    # write all the rows
    for ii in range(len(dat)):
        csvWriterObj.writerows(dat[ii])
    fid.close()

def GetDatasetInformation(infoFilename, filenameList):
    """Read dataset information file"""
    fid = open(infoFilename, 'r');
    csvReaderObj = csv.reader(fid, delimiter = '\t')
    datasetName = []
    acquisitionTime = []
    timeStamp = []
    timeNum = []
    header = []

    for lineIn in csvReaderObj:
        datasetName.append(lineIn[0])
        timeStamp.append(lineIn[1])
        acquisitionTime.append(lineIn[2])
        timeNum.append(lineIn[3])
        header.append(lineIn[4])

    acquisitionTime = np.array(acquisitionTime)
    acquisitionTime = acquisitionTime.astype(float)
    datasetName = np.array(datasetName)
    timeStamp = np.array(timeStamp)
    timeNum = np.array(timeNum)
    timeNum = timeNum.astype(float)
    header = np.array(header)

    # Get the information about the dataset
    datasetDescription = [] # header
    datasetTimeStr = [] # dataset time stamp string
    datasetTime = [] # dataset time stamp string
    datasetTimeNum = [] # epoch start time
    datasetAcquisitionTime = [] # acquisition  time

    for ii in range(0, len(filenameList)):
        print filenameList[ii]
        index = np.where(datasetName == filenameList[ii])[0][0]
        datasetDescription.append(header[index])
        datasetTimeStr.append(timeStamp[index])
        datasetTimeNum.append(timeNum[index])
        datasetTime.append(time.localtime(timeNum[index]))
        datasetAcquisitionTime.append(acquisitionTime[index])

    datasetDescription = np.array(datasetDescription)
    datasetTimeStr = np.array(datasetTimeStr)
    datasetTimeNum = np.array(datasetTimeNum)
    datasetAcquisitionTime = np.array(datasetAcquisitionTime)

    return (datasetDescription, datasetAcquisitionTime, datasetTime, datasetTimeNum, datasetTimeStr)


def WriteSummedSpectra(fullFilename,dat, timeStart, timeEnd):
    # open file for writing
    fid = open(fullFilename, 'wb')
    csvWriterObj = csv.writer(fid, delimiter = ',')
    # write all the rows
    for ii in range(len(dat)):
        csvWriterObj.writerow(dat[ii][:,timeStart:timeEnd].sum(axis = 1))
    fid.close()

def ReadSummedSpectra(fullFilename):
    # open file for writing
    fid = open(fullFilename, 'rb')
    dat = np.genfromtxt(fullFilename, delimiter = ',')
    fid.close()
    return dat

# created summed spectra files for multiple datasets
def CreateSummedSpectraFiles(basedirectory, filenamePrefixList, timeStart, timeEnd):
    for filenamePrefix in filenamePrefixList:
        dat = ReadData(filenamePrefix, basedirectory)
        fullFileName = basedirectory + '\\' + filenamePrefix + 'Summed.csv'
        WriteSummedSpectra(fullFileName, dat, timeStart, timeEnd)

def ReBinData(spectra, oldBinCenters, newBinEdges):
    binCenters = (newBinEdges[:-1] + newBinEdges[1:])/2
    spectraReBinned = np.zeros((spectra.shape[0], len(binCenters)))
    for ii in np.arange(len(binCenters)):
        cutt = (oldBinCenters >= newBinEdges[ii]) & (oldBinCenters < newBinEdges[ii+1])
        spectraReBinned[:, ii] = spectra[:,cutt].sum(axis = 1)
    return(spectraReBinned, binCenters)